Web development and Tech news Blog site. WEBISFREE.com

HOME > webdevetc

[Nuxtjs] Dynamically refreshing useFetch() with parameter and query string changes

Last Modified : 26 Feb, 2023 / Created : 24 Feb, 2023
716
View Count
In Nuxtjs, the useFetch() lifecycle hook at the page level is often used for server-side rendering.


"Can we re-execute useFetch()? What is the refresh method?"



If you use useFetch() and want to re-execute it because of changes in query strings or filtering, can you change the parameters and re-execute useFetch()? One way that might come to mind first is to use watch. You can set the query string value or parameter to detect in watch and fetch the data. In addition to this method, there is another way to do it without using watch, which we will explore below.





# Refreshing useFetch() in Nuxtjs


One way to re-execute useFetch() is to save the $fetch function, which is one of the values returned after executing the useFetch() hook, in a variable. When you want to execute it again, you can call the variable and the fetch function will be executed again.

To refresh useFetch():

  • Execute useFetch()
  • Save $fetch() from the returned object to a variable
  • Call the variable to re-execute fetch

The method is simple like this. Note that the returned object contains fetchState to check the state value and $fetch to re-execute the fetch function. So you can save this value as a component state value and call it later.


! useFetch() refresh Example


Let's create a simple example code to understand it better. The following Nuxtjs component has an empty state value called refreshFetch. Now, when you call the useFetch() hook inside the setup() function, save the returned $fetch as refreshFetch and call it later when needed. In this case, you can call refreshFetch() when the button is clicked.
<template>
  <button @click="refreshFetch">Refresh</button>
</template>

<script>
setup() {
  const refreshFetch = ref();

  const { $fetch } = useFetch(() => { fetchFunction });
  refreshFetch.value = $fetch;

  const onClickButton = () => {
    refreshFetch();
  }

  return {
    refreshFetch
  }
}
</script>

That's all there is to it. What are the benefits of re-executing useFetch()? First, since you don't need to use watch separately, the code is more concise and the logic is simpler.

By the way, if there is no specific event callback, and it is difficult to execute it directly, watch() can be more useful. So far, we have learned about the method to re-execute and refresh useFetch() when using the useFetch() hook.


Perhaps you're looking for the following text as well?

    Previous

    [JavaScript] Implementing text-to-speech functionality using speechSynthesis.

    Previous

    Resolving unable to use ports below 1000 in WSL local development environment.